﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK.Graphics.OpenGL4;
namespace Common {
    public class Texture2D : GlDisposableObjectBase {
        public Texture2D() {
            this.TextureId = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, this.TextureId);
        }
        public Texture2D(int textureId) {
            this.TextureId = textureId;
        }

        public int TextureId { get; }
        protected override void OnDispose() {
            GL.DeleteTexture(this.TextureId);
        }
        public void Bind() {
            GL.BindTexture(TextureTarget.Texture2D, this.TextureId);
        }
        public void Active(TextureUnit unit, Shader shader, string uniformName) {
            //unit = (TextureUnit)TextureUnit.Texture10;
            GL.ActiveTexture(unit);
            GL.BindTexture(TextureTarget.Texture2D, this.TextureId);
            int textureNumber = (int)unit - (int)TextureUnit.Texture0;
            shader.SetInt(uniformName, textureNumber);
        }
        public void CreateEmptyRGB(int width,int height) {
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, width, height, 0, PixelFormat.Rgb, PixelType.UnsignedByte, IntPtr.Zero);
        }
        public void SetTextureParameter(TextureParameterName parameterName,int value) {
            GL.TexParameter(TextureTarget.Texture2D, parameterName, value);
        }
        public void SetWrapS(TextureWrapMode wraps) {
            SetTextureParameter(TextureParameterName.TextureWrapS, (int)wraps);
        }
        public void SetWrapT(TextureWrapMode wrapT) {
            SetTextureParameter(TextureParameterName.TextureWrapT, (int)wrapT);
        }
        public void SetMagFilter(TextureMagFilter mag) {
            SetTextureParameter(TextureParameterName.TextureMagFilter, (int)mag);
        }
        public void SetMinFilter(TextureMinFilter min) {
            SetTextureParameter(TextureParameterName.TextureMinFilter, (int)min);
        }
        public static Texture2D Load(string path) {
            FileInfo fileInfo = new FileInfo(path);
            string extension = fileInfo.Extension.ToLower();
            int textureId;
            if (extension == ".dds") {
                textureId = DdsReader.LoadDds(path);

            } else if(extension==".bmp"){
                textureId = BmpReader.loadCustomBmp(path);
            } else {
                throw new EngineException($"texture format '{extension}' not supported");
            }
            return new Texture2D(textureId);
        }
    }
}
